const fs = require('fs');
const path = require('path');

/*const fullFileName = path.resolve(__dirname, 'files', 'a.json');
fs.readFile(fullFileName,((err, data) => {
    if (err) {
        console.error(err);
        return ;
    }
    console.log(data.toString());
}));*/

/*callback 方式获取文件内容*/

/*
function getFileContent(fileName, callback) {
    const fullFileName = path.resolve(__dirname, 'files', fileName);
    fs.readFile(fullFileName, ((err, data) => {
        if (err) {
            console.error(err);
            return;
        }
        callback(JSON.parse(data.toString()));
    }));
}

/!*测试 callback-hell*!/
getFileContent('a.json', aData => {
    console.log('a data:', aData);
    getFileContent(aData.next, bData => {
        console.log('b data:', bData);
        getFileContent(bData.next, cData => {
            console.log('c data:', cData);
        })
    })
});*/

function getFileContent(fileName) {
    return new Promise(((resolve, reject) => {
        const fullFileName = path.resolve(__dirname, 'files', fileName);
        fs.readFile(fullFileName, ((err, data) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(JSON.parse(data.toString()));
        }));
    }))
}

/*Promise方式*/
/*getFileContent('a.json').then(aData => {
    console.log('a data:', aData);
    return getFileContent(aData.next);
}).then(bData => {
    console.log('b data:', bData);
    return getFileContent(bData.next);
}).then(cData => {
    console.log('c data:', cData);
});*/

/*async/await方式*/
async function readFileData() {
    try {
        // 同步写法
        const aData =await getFileContent('a.json');
        console.log('a data:', aData);
        const bData = await getFileContent(aData.next);
        console.log('b data:', bData);
        const cData = await getFileContent(bData.next);
        console.log('c data:', cData);
    }catch (e) {
        console.error(e);
    }
}

readFileData();

/*test*/
/*
async function readData() {
    return await getFileContent('a.json');
}

async function test() {
    const data = await readData();
    console.log(data);
}
*/

test();

// koa2